package com.lagou.minicat.connector;

import com.lagou.minicat.service.Service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Connector
 * @Description 监听socket端口
 * @Author playboy
 * @Date 2021/5/22 2:07 下午
 * @Version 1.0
 **/
public class Connector extends Thread {

	/**
	 * 每一个connector都有一个线程池
	 */
	private ThreadPoolExecutor poolExecutor =
			new ThreadPoolExecutor(10,
					10,
					60L,
					TimeUnit.SECONDS,
					new ArrayBlockingQueue<Runnable>(20),
					Executors.defaultThreadFactory(),
					new ThreadPoolExecutor.AbortPolicy());

	/**
	 * 监听端口
	 */
	private int port;

	private Service service;

	public Connector(int port) {
		this.port = port;
	}

	public Service getService() {
		return service;
	}

	public void setService(Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		try {
			ServerSocket serverSocket = new ServerSocket(port);
			System.out.println("端口prot:" + port + "开始监听");
			while (true) {
				Socket accept = serverSocket.accept();
				AccpectHandle handle = new AccpectHandle(accept, service);
				poolExecutor.execute(handle);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
